<?php


namespace app\admin\controller;


use app\admin\model\CouponModel;
use app\admin\model\GoodsModel;
use app\admin\model\MaterialModel;
use app\admin\model\RoleUserModel;
use app\admin\model\UserModel;
use app\admin\model\WechatUserModel;
use cmf\controller\AdminBaseController;
use think\Db;
use think\Exception;

class CouponController extends AdminBaseController
{
    public function index()
    {
        $admin_id = cmf_get_current_admin_id();
        $role_id = RoleUserModel::where('user_id', $admin_id)->value('role_id');
        $role_id = $role_id ? $role_id : 1;
        $this->assign('role_id', $role_id);
        if ($this->request->isAjax()) {
            $data = $this->request->param();
            $num = 10;
            $page = isset($data['page']) && $data['page'] ? $data['page'] : 1;
            $where = [];
            $admin_id = cmf_get_current_admin_id();
            $admin_info = UserModel::get($admin_id);
            if ($admin_info['company_id']) {
                $where[] = ['company_id', '=', $admin_info['company_id']];
            }
            if (isset($data['duration']) && $data['duration']) {
                $where[] = ['create_time', 'between time', [$data['duration'][0], $data['duration'][1]]];
            }
            $list = CouponModel::withCount('card_list')->where($where)
                ->order('create_time desc')
                ->paginate($num, false, ['page' => $page])
                ->each(function ($item) {
                    if ($item['begin_timestamp'] && $item['end_timestamp']) {
                        $begin_timestamp = date('Y-m-d', $item['begin_timestamp']);
                        $end_timestamp = date('Y-m-d', $item['end_timestamp']);
                        $item['activity_time'] = [$begin_timestamp, $end_timestamp];
                    }
                    if ($item['use_condition']) {
                        $item['use_condition'] = GoodsModel::where('id', 'in', $item['use_condition'])->all();
                    }
                    return $item;
                });
            $this->success('', '', $list);
        }
        return $this->fetch();
    }

    public function update()
    {
        if ($this->request->post()) {
            try {
                Db::startTrans();
                $data = $this->request->param();
                $id = isset($data['id']) && $data['id'] ? $data['id'] : 0;
                if ($id) {
                    $coupon = CouponModel::get($data['id']);
                } else {
                    $coupon = new  CouponModel();
                }
                $admin_id = cmf_get_current_admin_id();
                $admin_info = UserModel::get($admin_id);
                if ($admin_info['company_id']) {
                    $coupon->company_id = $admin_info['company_id'];
                } else {
                    $coupon->company_id = $data['company_id'];
                }
                $coupon->title = $data['title'];
                if (isset($data['end_timestamp']) && $data['end_timestamp']) {
                    $coupon->end_timestamp = strtotime($data['end_timestamp'] . ' 23:59:59');;
                }
                if (isset($data['activity_time']) && $data['activity_time']) {
                    $begin_timestamp = strtotime($data['activity_time'][0] . ' 00:00:00');
                    $end_timestamp = strtotime($data['activity_time'][1] . ' 23:59:59');
                    $coupon->begin_timestamp = $begin_timestamp;
                    $coupon->end_timestamp = $end_timestamp;
                }

                if (isset($data['use_condition']) && $data['use_condition']) {
                    $goods_list = $data['use_condition'];
                    $ids = [];
                    foreach ($goods_list as $key => $value) {
                        $ids[] = $value['id'];
                    }
                    $coupon->use_condition = implode(',', $ids);
                }
                $coupon->coupon_type = $data['coupon_type'];
                $coupon->type = $data['type'];
                $coupon->code_type = $data['code_type'];
                $coupon->date_info_type = $data['date_info_type'];
                $coupon->quantity = $data['quantity'];
                $coupon->get_limit = $data['get_limit'];
                $coupon->is_receive = $data['is_receive'];
                $coupon->notice = $data['notice'];
                $coupon->description = $data['description'];
                $coupon->fixed_begin_term = $data['fixed_begin_term'];
                $coupon->fixed_term = $data['fixed_term'];
                $coupon->least_cost = isset($data['least_cost']) && $data['least_cost'] ? $data['least_cost'] : 0;
                $coupon->reduce_cost = isset($data['reduce_cost']) && $data['reduce_cost'] ? $data['reduce_cost'] : 0;
                $coupon->color = $data['color'];
                $coupon->discount = isset($data['discount']) && $data['discount'] ? $data['discount'] : 0;
                $coupon->gift = isset($data['gift']) && $data['gift'] ? $data['gift'] : '';
                $coupon->fixed_term = $data['fixed_term'];
                $coupon->logo_url = $data['logo_url'];
                $coupon->brand_name = $data['brand_name'];
                $res = $coupon->save();
                if ($res) {
                    if (empty($id)) {
                        $id = $coupon->id;
                    }
                    $coupon_info = CouponModel::get($id);
                    $logo_material = MaterialModel::where([
                        'local_url' => $coupon_info['logo_url'],
                        'company_id' => $coupon_info['company_id']])
                        ->find();
                    if ($logo_material) {
                        $coupon_info['logo_url'] = $logo_material['wechat_url'];
                    } else {
                        $logo_data['type'] = 'img';
                        $logo_data['company_id'] = $coupon_info['company_id'];
                        $logo_data['path'] = CMF_ROOT . 'public' . $coupon_info['logo_url'];
                        $result1 = hook('upload_material', $logo_data);
                        $logo_material = new MaterialModel([
                            'company_id' => $coupon_info['company_id'],
                            'local_url' => $coupon_info['logo_url'],
                            'media_id' => $result1[0]['media_id'],
                            'wechat_url' => $result1[0]['url']

                        ]);
                        $logo_material->save();
                        $card_info['logo_url'] = $result1[0]['url'];
                    }
                    $res = hook('create_coupon', $coupon_info);

                    if (isset($coupon_info['card_id']) && empty($coupon_info['card_id'])) {
                        CouponModel::where('id', $id)->update(['card_id' => $res[0]['card_id'], 'status' => 'CARD_STATUS_NOT_VERIFY']);
                    }
                    Db::commit();
                    $this->success('更新成功', '', $res);
                } else {
                    throw new Exception('更新失败');
                }
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }

        }
    }

    public function update_status()
    {
        if ($this->request->isAjax()) {
            $data = $this->request->param();
            $param['company_id'] = $data['company_id'];
            $param['card_id'] = $data['card_id'];
            $coupon_info = CouponModel::where('card_id', $data['card_id'])->find();
            $res = hook('get_card_status', $param);
            if ($res[0]['errcode'] == 0) {
                $card_info = $res[0]['card'];
                $card_type = '';
                switch ($coupon_info['coupon_type']) {
                    case 'CASH':
                        $card_type = 'cash';
                        break;
                    case 'DISCOUNT':
                        $card_type = 'discount';
                        break;
                    case 'GIFT':
                        $card_type = 'gift';
                        break;
                }
                $status = $card_info[$card_type]['base_info']['status'];
                $coupon_info->status = $status;
                $coupon_info->save();
                switch ($status) {
                    case 'CARD_STATUS_NOT_VERIFY':
                        $this->success('等待审核中', '', $card_info);
                        break;
                    case 'CARD_STATUS_VERIFY_FAIL':
                        $this->success('审核失败');
                        break;
                    case 'CARD_STATUS_VERIFY_OK':
                        $this->success('审核成功');
                        break;
                    case 'CARD_STATUS_USER_DELETE':
                        $this->success('卡券被商户删除');
                        break;
                    case 'CARD_STATUS_DISPATCH':
                        $this->success('在公众平台投放过的卡券');
                        break;
                    default:
                        $this->error('获取信息失败');
                        break;
                }
            } else {
                $this->error('获取信息失败');
            }

        }
    }

    public function send_card()
    {
        if ($this->request->isPost()) {
            $data = $this->request->param();
            $id = isset($data['id']) && $data['id'] ? $data['id'] : 0;
            $coupon_info = CouponModel::get($id);
            if (empty($coupon_info)) {
                $this->error('优惠券不存在或已被删除');
            }
            if ($coupon_info['status'] != 'CARD_STATUS_VERIFY_OK') {
                $this->error('优惠券未通过审核');
            }
            $param['company_id'] = $coupon_info['company_id'];
            $param['card_id'] = $coupon_info['card_id'];
            $param['openid'] = $data['openid_list'];
            $res = hook('wechat_send_card', $param);
            $this->success('发送成功', '', $res);
        }
    }
}
